from MediaInfoDLL import * 
from PyFlac.Carbon import CarbonUtils
from PyFlac.Carbon import CarbonJob
from PyFlac.Carbon import CarbonSocketLayer
from PyFlac.Ardome import ArdXML
from PyFlac import TimeCode
from PyFlac import TimeCodeLib
import sys
import shutil

SMB_PATH_IN   = '\\\\10.221.173.151\\VOD\\SD\\'
SMB_PATH_OUT  = '\\\\10.221.173.151\\VOD\\Outbox\\'
GUID          = '{CB4FDFA5-C235-4D10-BB7D-2AE56CB09287}'
MEDIA_PATH    = '/data/VOD/SD/'


def msToFrames(ms):
        f = 1000.0 / 29.97
        return int(round( ms / f ))



Subject   = "FOD: %source%"
Recipient = "emiliano.billi@fox.com; guillermo.bertossi@fox.com"


def CutSegment (mxf, cut_info, basename, carbon_host, carbon_guid, src_path, dst_path, notif):

	carbon = CarbonSocketLayer.CarbonSocketLayer(carbon_host)

	jobXml = CarbonUtils.CreateCarbonXMLJob(src_path, mxf, cut_info, [{'d_guid': carbon_guid, 'd_basename': basename, 'd_path': dst_path, 'd_start_tc': "00:00:00;00"}], None, notif)

	return CarbonJob.CarbonJob(carbon, jobXml)


def CutMediaSegments(mxf, Segments, carbon_host, carbon_guid, src_path, dst_path):
	
	if os.path.isfile(MEDIA_PATH+mxf):

		MI = MediaInfo()
		MI.Open(MEDIA_PATH+mxf)
		delay = MI.Get(Stream.Video, 0, u"Delay")
		MI.Close()
		
		# delay are in ms, needs convert to frames 
		

		In = TimeCodeLib.TimeCode()
		Out = TimeCodeLib.TimeCode()
		Dur = TimeCodeLib.TimeCode()
		i = 1
		cut_info = []

		Body = "Informacion sobre los Segmentos:\n\n"


		frames =  msToFrames(int(delay))	
		for s in Segments:
			
			Dur.setTimeCode(s.total_seg_length)
			
			if i == 1:
				
				In.setTimeCode("00:00:00;00")
				Out = TimeCodeLib.timeCodeFromFrames(Dur.getFrames(), Dur.getFrameRate())
			else:
				In = TimeCodeLib.timeCodeFromFrames(Out.getFrames(), Out.getFrameRate())
				Out = Out + Dur

			print "In: " + In.getTimeCode()
			print "Out: " + Out.getTimeCode()

			Body = Body + "SEGMENTO " + str(i) + " IN: " + In.getTimeCode() + "\nSEGMENTO " + str(i) +" OUT: " + Out.getTimeCode() + "\n\n"

			tcin  = TimeCode.TimeCode(s.SOM)
        		tcout = TimeCode.TimeCode(s.EOM)
		

        		framesin  = tcin.GetFramesFromZero() - frames
        		framesout = tcout.GetFramesFromZero() - frames

			cut_info.append({ 'in' : str(CarbonUtils.FramesToCarbonFramesUnit(framesin)), 'out': str(CarbonUtils.FramesToCarbonFramesUnit(framesout)) })
			
			i = i + 1

		
		notif = CarbonUtils.MailNotify(None, {'Body': Body, 'Subject': Subject, 'Recipient': Recipient}, None)

		job = CutSegment(mxf, cut_info, mxf, carbon_host, carbon_guid, src_path, dst_path, notif)
		job.Start()




list = os.listdir(MEDIA_PATH)
for i in list: 

	if not i.endswith(".xml"):
		continue	

	os.system("ascii " + MEDIA_PATH+i + " /tmp/"+i)
	
	
	xml = ArdXML.ArdXML("/tmp/"+i)

	shutil.move("/tmp/"+i, MEDIA_PATH+"proc/"+i)


	(mxf,e, x) = i.split(".")

	mxf = mxf + ".mxf"

	print "BASE: " + MEDIA_PATH+mxf
	os.remove(MEDIA_PATH+i)

	for s in xml.Metadata.segments:
		print s.SOM + '-' + s.EOM


	CutMediaSegments(mxf, xml.Metadata.segments, '10.221.173.95', GUID, SMB_PATH_IN, SMB_PATH_OUT)
